package router

import (
	"dhuviewer/dto"
	services "dhuviewer/services"
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

func ReplyRouter(rg *gin.RouterGroup) {
	replyGroup := rg.Group("/")

	replyGroup.GET("/stat/replyByDate", func(c *gin.Context) {
		payload, err := HelpcheckJWT(c)
		if err != nil {
			return
		}
		res, err := services.StatReply(uuid.MustParse(payload.Uid))
		HelpErrorWithReturn(c, err, res)
	})

	replyGroup.GET("/stat/replyByUid", func(c *gin.Context) {
		payload, err := HelpcheckJWT(c)
		if err != nil {
			return
		}
		res, err := services.StatCom(uuid.MustParse(payload.Uid))
		HelpErrorWithReturn(c, err, res)
	})

	replyGroup.GET("/viewByGid/:gid", func(c *gin.Context) {
		gid := c.Param("gid")
		_, err := HelpcheckJWT(c)
		if err != nil {
			return
		}
		replyRes, err := services.ListReplyByGid(uuid.MustParse(gid))
		HelpErrorWithReturn(c, err, replyRes)
	})

	replyGroup.GET("/viewByUid/:uid", func(c *gin.Context) {
		uid := c.Param("uid")
		// fmt.Println(gid)
		payload, err := HelpcheckJWT(c)
		if err != nil {
			return
		}
		if uid == "" {
			uid = payload.Uid
		}
		replyRes, err := services.ListReplyByUid(uuid.MustParse(uid))
		HelpErrorWithReturn(c, err, replyRes)
	})

	replyGroup.POST("/create", func(c *gin.Context) {
		payload, err := HelpcheckJWT(c)
		if err != nil {
			return
		}
		replyInfo := new(dto.Reply)
		c.ShouldBind(&replyInfo)
		fmt.Println(replyInfo)
		rid, err := services.CreateReply(replyInfo, uuid.MustParse(payload.Uid), payload.Username)
		if err != nil {
			c.JSON(200, gin.H{
				"status": 40000,
			})
			return
		} else {
			c.JSON(200, gin.H{
				"status": 20000,
				"rid":    rid,
			})
		}
	})

	replyGroup.DELETE("/delByRid/:rid", func(c *gin.Context) {
		rid := c.Param("rid")
		payload, err := HelpcheckJWT(c)
		if err != nil {
			return
		}
		if payload.Level == "admin" {
			err = services.DeleteReply(uuid.MustParse(rid))
		} else {
			err = services.DeleteReplySelf(uuid.MustParse(rid), uuid.MustParse(payload.Uid))
		}
		HelpErrorWithCode(c, err)
	})

	replyGroup.DELETE("/delByGid/:gid", func(c *gin.Context) {
		gid := c.Param("gid")
		_, err := HelpcheckJWT(c)
		if err != nil {
			return
		}
		err = services.DeleteReplyByGid(uuid.MustParse(gid))
		HelpErrorWithCode(c, err)
	})
}
